﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;
using Brc_DSB.GetWay.Configuration;
using Brc_DSB.GetWay.Model;
using Dapper;
using Ocelot.Cache;
using Ocelot.Configuration;

namespace Brc_DSB.GetWay.DataBase
{
    public class RetryRepository : IRetryRepository
    {
        private readonly DbConfiguration _option;
        private readonly IOcelotCache<GetWay_ReRouteRetry> _cache;
        public RetryRepository(DbConfiguration option, IOcelotCache<GetWay_ReRouteRetry> cache)
        {
            _option = option;
            _cache = cache;
        }
        public async Task<GetWay_ReRouteRetry> GetRetryPolicy(string path)
        {
            var sql = @"
SELECT 
    TOP 1
	A.* 
FROM 
	[dbo].[GetWay_ReRouteRetry] A
INNER JOIN 
	[dbo].[GetWay_ReRoute] B
	ON A.ReRouteId=B.ReRouteId
INNER JOIN 
	[dbo].[GetWay_ConfigReRoutes] C
	ON B.ReRouteId=C.ReRouteId
INNER JOIN 
	[dbo].[GetWay_Configuration] D
	ON C.GetWayId=D.GetWayId
WHERE 
	D.InfoStatus=1
	AND
	B.UpstreamPathTemplate=@path
	AND
	B.InfoStatus=1
	AND
	A.[Status]=1
";
            using (var connection = new SqlConnection(_option.DbConnectionStrings))
            {
                //如果启用了权限缓存，那么久先从缓存中取，取不到就去数据库取，然后放入缓存
                GetWay_ReRouteRetry retryResult = null;
                var key = path;
                if (_option.IsEnableRetry)
                {

                    retryResult = _cache.Get(key, "RetryPolicy");
                }
                if (retryResult == null)
                {
                    try
                    {
                        retryResult = await connection.QueryFirstOrDefaultAsync<GetWay_ReRouteRetry>(sql,new { path });
                        _cache.Add(key, retryResult, TimeSpan.FromMinutes(_option.RetryCacheTime), "RetryPolicy");
                    }
                    catch(Exception e)
                    {
                        throw e;
                    }
                }
                return retryResult;
            }
        }
    }
}
